package com.audio.play;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.AsyncTask;

public class PlaySoundTask  extends AsyncTask<Void, Void, Void> {
	AudioTrack track;

	float frequency;
	float increment;
	float angle = 0;
	short samples[] = new short[1024];
	boolean isPlaying = false;
	AudioPlayActivity activity;

	public void setPlaying(boolean isPlaying) {
		this.isPlaying = isPlaying;
	}
	public void setFrequency(float frequency) {
		this.frequency = frequency;
	}
	@Override
	protected void onPreExecute() {
		int minSize = AudioTrack.getMinBufferSize(44100,
				AudioFormat.CHANNEL_CONFIGURATION_MONO,
				AudioFormat.ENCODING_PCM_16BIT);
		track = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
				AudioFormat.CHANNEL_CONFIGURATION_MONO,
				AudioFormat.ENCODING_PCM_16BIT, minSize,
				AudioTrack.MODE_STREAM);
		track.play();
	}

	@Override
	protected Void doInBackground(Void... params) {
//		while (isPlaying) {
//			for (int i = 0; i < samples.length; i++) {
//				increment = (float) (2 * Math.PI) * frequency / 44100;
//				samples[i] = (short) ((float) Math.sin(angle) * Short.MAX_VALUE);
//				angle += increment;
//			}
//
//			track.write(samples, 0, samples.length);
//		}
		
		SandBox sb = new SandBox();
		try {
			byte[] buffer = sb.modulate( "0000Test!0000" );
			track.write(buffer, 0, buffer.length);
			
			
			ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
			ShortBuffer shortBuffer = byteBuffer.asShortBuffer();
			String result = sb.demodulateSampleBuffer( shortBuffer );
			activity.result = result;
			
			activity.mHandler.sendEmptyMessage(0);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
}
